import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_django.settings')

import django
django.setup()

from rango.models import Category, Page


def populate():

    python_pages = [
            {'title': 'Official Python Tutorial',
            'url': 'http://docs.python.org/2/tutorial/',
            'views': 408},
            {'title': 'How to Think like a Computer Scientist',
            'url': 'http://www.greeteapress.com/thinkpython/',
            'views': 123},
            {'title': 'Learn Python in 10 Minutes',
            'url': 'http://www.korokithakis.net/tutorials/python/',
            'views': 97}
            ]


    django_pages = [
            {"title": "Official Django Tutorial",
            "url": "http://docs.djangoproject.com/en/1.9/intro/tutorial01/",
            "views": 89},
            {"title": "Django Books",
            "url": "http://www.djangorocks.com/",
            "views": 129},
            {"title": "How to Tango with Django",
            "url": "http://www.tangowithdjango.com/",
            "views": 233}
            ]


    other_pages =[ 
            {"title": "Bottle",
            "url": "http://bottlepy.org/docs/dev/",
            "views": 52},
            {"title": "Flask",
            "url": "http://flask.pocoo.org",
            "views": 94}
            ]

    tornado_pages = [
            {'title': 'Tornado Web Server',
            'url': 'http://www.tornadoweb.org/en/stable/',
            'views': 85},
            {'title': 'An introduction to the Tornado Python web app framework',
            'url': 'http://www.opensource.com/article/18/6/tornado-framework',
            'views': 22}
            ]

    cats = {('Python', 128, 64): {'pages': python_pages},
            ('Django', 64, 32): {'pages': django_pages},
            ('Tornado', 0, 0): {'pages': tornado_pages},
            ('Other Frameworks', 32, 16): {'pages': other_pages}}


    for cat, cat_data in cats.items():
        c = add_cat(cat)

        for p in cat_data['pages']:
            add_page(c, p['title'], p['url'], p['views'])

    for c in Category.objects.all():
        for p in Page.objects.filter(category=c):
            print("- {0} - {1}".format(str(c), str(p)))


def add_cat(cat_tuple):
        c = Category.objects.get_or_create(name=cat_tuple[0])[0]
        c.views = cat_tuple[1]
        c.likes = cat_tuple[2]
        c.save()
        return c


def add_page(cat, title, url, views=0):
        p = Page.objects.get_or_create(category=cat, title=title)[0]
        p.url = url
        p.views = views
        p.save()
        return p


if __name__ == "__main__":
    print("Starting Rango population script...")
    populate()
